﻿namespace Leetcode.N0427;

public class Solution
{
    public Node Construct(int[][] grid)
    {
        return this.Construct(grid, 0, 0, grid.Length);
    }

    private Node Construct(int[][] grid, int fromRow, int fromCol, int count)
    {
        if (count == 1)
        {
            return new Node(grid[fromRow][fromCol] == 1, true);
        }
        var children = new Node[4];
        count /= 2;
        var topLeft = this.Construct(grid, fromRow, fromCol, count);
        var topRight = this.Construct(grid, fromRow, fromCol + count, count);
        var bottomLeft = this.Construct(grid, fromRow + count, fromCol, count);
        var bottomRight = this.Construct(grid, fromRow + count, fromCol + count, count);
        var isLeaf = topLeft.val == topRight.val && topLeft.val == bottomLeft.val && bottomLeft.val == bottomRight.val;
        if (isLeaf && topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf)
        {
            return new Node(topLeft.val, isLeaf);
        }
        else
        {
            return new Node(true, false, topLeft, topRight, bottomLeft, bottomRight);
        }
    }
}